import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;

import com.google.gson.Gson;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class gameServlet extends HttpServlet implements Servlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		String[] actions = {"new_game", "restart_game"};
		//index or -1 if not found
		int actionIndex = ArrayUtils.indexOf(actions, action);
		
		switch (actionIndex) {
			case 0:
				this.getGame(request, response);
				break;
			default:
				break;		
		}		
	}
	
	//get the current game from session or create a new one and output json data of scores
	private void getGame(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		PokerGame game = 
			(PokerGame)req.getSession(true).getAttribute("pokerappgame");
		int players = 10;
		int startingScore = 1500;
		int personPosition = 1;
		
		if(game == null) {
			game = new PokerGame(players, startingScore, personPosition);
			req.getSession().setAttribute("pokerappgame", game);
		}
		Map<String, String> result = new LinkedHashMap<String, String>();
		
		//add all player scores
		for (int i = 0; i < players; i++) {
			result.put("score_"+i, Integer.toString(game.getPlayer(i).getScore()));
		}
		//add user 
		result.put("person_card1", game.getPlayer(game.getPersonPosition()).getCard1().toString());
		result.put("person_card2", game.getPlayer(game.getPersonPosition()).getCard2().toString());
		result.put("person_position", Integer.toString(game.getPersonPosition()));		
		
	    String json = new Gson().toJson(result);

	    resp.setContentType("application/json");
	    resp.setCharacterEncoding("UTF-8");
	    resp.getWriter().write(json);
	}	
}
